package com.yunjian.common.utils;

import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.sun.mail.util.MailSSLSocketFactory;
import com.yunjian.core.dto.MailAuthenticator;
import com.yunjian.core.dto.SecurityContext;

public class MailUtils {
	
	private static Logger logger = LoggerFactory.getLogger(MailUtils.class); 
	
	public static String mail_user = "zwx13148701472@163.com";
	public static String mail_password = "0755020b";	//smtp登录都是使用授权码登录而不是邮箱密码
	public static String mail_transport_protocol = "smtp";
	public static String mail_smtp_host = "smtp.163.com";
	public static String mail_smtp_port = "25";
	public static String mail_smtp_auth = "true";
	public static String mail_smtp_timeout = "10000";
	
    public static Properties getMailProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.timeout",mail_smtp_timeout);
        properties.setProperty("mail.smtp.host", mail_smtp_host);
        properties.put("mail.user", mail_user);
        properties.put("mail.password", mail_password);
        properties.put("mail.transport.protocol", mail_transport_protocol);
        properties.put("mail.smtp.host", mail_smtp_host);
        properties.put("mail.smtp.port", mail_smtp_port);
        properties.put("mail.smtp.auth", mail_smtp_auth);
        return properties;
    }

    public static boolean sendMail(String to, String code) {
        if (to != null) {
            try {
                Properties prop = getMailProperties();
                String user = prop.getProperty("mail.user");
                String password = prop.getProperty("mail.password");
                MailAuthenticator auth = new MailAuthenticator(user, password);
                Session session = Session.getInstance(prop, auth);
                session.setDebug(true);
                Transport transport = session.getTransport("smtp");
                transport.connect(prop.getProperty("mail.smtp.host"),prop.getProperty("mail.user"), prop.getProperty("mail.password"));

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(user));
                message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
                message.setSubject("邮箱验证码");

                MimeMultipart mimeMultipart = new MimeMultipart("mixed");
                message.setContent(mimeMultipart);
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeMultipart.addBodyPart(mimeBodyPart);
                MimeMultipart bodyMultipart = new MimeMultipart("related");
                mimeBodyPart.setContent(bodyMultipart);
                MimeBodyPart htmlPart = new MimeBodyPart();
                bodyMultipart.addBodyPart(htmlPart);
                String content = "验证码为{0}，有效时间5分钟，请妥善保管。" ;
                htmlPart.setContent(MessageFormat.format(content, code), "text/html;charset=utf-8");
                
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }catch (Exception e){
            	logger.error("邮件发送失败", e);
            	return false;
            }
            return true;
        } else {
            return false;
        }
    }
    
    public static void sendMail2(String email, String code){
        try {
            //设置发件人
            String from = mail_user;
            //设置邮件发送的服务器，这里为QQ邮件服务器
            String host = "smtp.163.com";
            //获取系统属性
            Properties properties = System.getProperties();
            //SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            //设置系统属性
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.auth", "true");

            //获取发送邮件会话、获取第三方登录授权码
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, "0755020b"); 
                }
            });
            Message message = new MimeMessage(session);
            //防止邮件被当然垃圾邮件处理，披上Outlook的马甲
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

            //邮件标题
            String language = SecurityContext.getLanguage();
            String subject = "";
            String content = "";
            if(StringUtils.isEmpty(language)){
                language = "zh_CN";
            }
            if(language.equals("zh_CN")) {
            	subject = "验证码";
            	content = "验证码是" + code + "，有效时间五分钟，请妥善保管。";
            }else {
            	subject = LanguageUtils.getValueByKey("email.verify.code");
            	String text = LanguageUtils.getValueByKey("email.content");
            	content = MessageFormat.format(text, code);
            }
            message.setSubject(subject);
            BodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(content);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodyPart);
            message.setContent(multipart);
            Transport.send(message);
            logger.info("向用户{}发送邮件成功", email);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}